package com.itcpeng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itcpeng.constant.MessageConstant;
import com.itcpeng.constant.RedisMessageConstant;
import com.itcpeng.entity.Result;
import com.itcpeng.exception.MyException;
import com.itcpeng.pojo.Order;
import com.itcpeng.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping(value = "/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping(value = "/submit")
    public Result submit(@RequestBody Map<String, String> map) throws MyException {
        Jedis jedis = jedisPool.getResource();
        //验证码有效期
        String telephone = map.get("telephone");
        String key = "Order_" + RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
        //redis中的验证码
        String s = jedis.get(key);
        if (StringUtils.isEmpty(s)) {
            //空值或者没有获取验证码
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        //有值   编码规范:先把不符合条件的处理完  后再处理符合条件的
        if (!s.equals(map.get("validateCode"))) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //清除验证码
        jedis.del(key);
        //调用业务
        map.put("orderType", "微信预约");
        Order order = orderService.submitOrder(map);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS, order);
    }

    @PostMapping(value = "/findById")
    public Result findById(Integer id) {
        //调用业务查询
        Map<String, String> date = orderService.findById(id);
        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, date);
    }
}
